/**
 * 
 */
package com.cipe.cmrs.controllers.payment;

import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.ModelAndView;

import com.cipe.cmrs.bean.PaymentRequestBean;

/**
 * @author Incepio
 * 
 */
@Controller
@RequestMapping("/secure/showAddPaymentrequest.do")
public class AddPaymentController extends AbstractPaymentController {

    /**
	 * 
	 */
    private static final long serialVersionUID = 6992545936182261895L;

    private static final String FORM_VIEW = "payment/addPaymentrequest";

    public AddPaymentController() {
        setFormView(FORM_VIEW);
        setSuccessView(FORM_VIEW);
    }

    @ModelAttribute(COMMAND_NAME)
    public PaymentRequestBean getCommand() {
        PaymentRequestBean bean = new PaymentRequestBean();
        bean.setCurrentlyresponsible(getText("status.responsible.payment.process.financeassistant"));
        return bean;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ModelAndView onSubmit(@ModelAttribute(COMMAND_NAME) PaymentRequestBean bean, BindingResult result,
        HttpServletRequest request, SessionStatus status) {
        ModelAndView mav = null;
        validator.validate(result, bean);
        if (result.hasErrors()) {
            mav = getFormView(bean, request);
            mav.addAllObjects(result.getModel());
            saveError(request, result.getGlobalErrors());
        } else {
            try {
                String action = request.getParameter(DEFAULT_SUBMIT_NAME);
                if (getText("editPaymentrequest.button.saveAndAddNew").equalsIgnoreCase(action)) {
                    paymentrequestService.savePaymentrequest(bean, getUserId(request));
                    bean = getCommand();
                } else {
                    bean = paymentrequestService.savePaymentrequest(bean, getUserId(request));
                }

                saveMessage(request, getText("editPaymentrequest.message.success"));
                status.setComplete();
                mav = getSuccessView(bean, request).addObject(COMMAND_NAME, bean);
            } catch (Exception e) {
                e.printStackTrace();
                logger.error(getText("error.transaction"), e);
                saveError(request, getText("error.transaction"));
                mav = getFormView(bean, request);
            }
        }
        return mav;
    }
}
